package sample.note;

import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.SneakyThrows;
import sample.note.storage.Repository;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Map;

import static sample.note.AppWrapper.cheers;

public class ExportActivity extends AppCompatActivity {
    TextView txt;
    Repository repo;
    final Gson gson = new GsonBuilder().create();

    @SneakyThrows
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_export);

        repo = new Repository(this);
        txt = findViewById(R.id.txt);

        output();

    }

    @SneakyThrows
    void output(){
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            txt.append("External storage Not available.\n");
            return;
        }
        File folder = this.getExternalFilesDir(File.separator);
        if(!folder.exists()){
            cheers("create folder");
            folder.mkdirs();
        }
        File file=new File(folder,this.getPackageName() + ".txt");
        txt.append(file.getAbsolutePath() + "\n");
        FileOutputStream out=new FileOutputStream(file);

        int limit = 1024;
        int offset = 0;
        ArrayList<Map<String, String>> rows;
        rows = repo.select(String.valueOf(limit), String.valueOf(offset));
        if(rows == null){
            txt.append("Not Found.\n");
            return;
        }
        while (rows.size() > 0) {
            for(Map i: rows){
                String s = gson.toJson(i);
                txt.append(s + "\n");
                out.write(s.getBytes());
                out.write("\n".getBytes());
            }

            offset += limit;
            rows = repo.select(String.valueOf(limit), String.valueOf(offset));
        }
        out.close();
        txt.append("Done!\n");
    }
}
